// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-25

package detail

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib/authorizer"
)

// Logic
// 订单详情.
type Logic struct {
	auth     *authorizer.Authentication
	request  *Request
	response *Response

	arcade *models.Arcades
	has    bool
	order  *models.Order
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	if err = db.Transaction(ctx,
		o.OpenOrder,
		o.OpenOrderItem,
		o.OpenOrderPayKind,
		o.OpenArcade,
	); err != nil {
		return res.WithError(err)
	}
	return res.With(o.response)
}

func (o *Logic) OpenArcade(ctx context.Context, sess *db.Session) (err error) {
	// 1. 查询钓场.
	if o.arcade, o.has, err = services.NewArcadesService(sess).Dao.GetById(ctx, o.order.ArcadeId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 校验钓场.
	if !o.has {
		err = errs.ErrArcadeNotFound
		return
	}

	// 3. 校验完成.
	o.response.WithArcade(o.arcade)
	return
}

func (o *Logic) OpenOrder(ctx context.Context, sess *db.Session) (err error) {
	// 1. 查询订单.
	if o.order, o.has, err = services.NewOrderService(sess).Dao.GetByMap(ctx, map[string]any{
		"order_no": o.request.OrderNo,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 校验订单
	if !o.has || o.order.UserId != o.auth.UserId {
		err = errs.ErrOrderNotFound
		return
	}

	// 3. 校验成功.
	o.response.With(o.order)
	return
}

func (o *Logic) OpenOrderItem(ctx context.Context, sess *db.Session) (err error) {
	var list []*models.OrderItem

	// 1. 读取列表.
	if list, err = services.NewOrderItemService(sess).Dao.ListByMap(ctx, map[string]any{
		"order_id": o.order.Id,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 遍历条目.
	for _, item := range list {
		o.response.AddItem(item)
	}
	return
}

func (o *Logic) OpenOrderPayKind(ctx context.Context, sess *db.Session) (err error) {
	var list []*models.OrderPayKind

	// 1. 读取列表.
	if list, err = services.NewOrderPayKindService(sess).Dao.ListByMap(ctx, map[string]any{
		"order_id": o.order.Id,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 遍历支付.
	for _, item := range list {
		o.response.AddPayKind(item)
	}
	return
}
